package com.example.tutorial.reminder;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.view.WindowManager;

import com.example.tutorial.model.DaoMaster;
import com.example.tutorial.model.DaoMaster.DevOpenHelper;
import com.example.tutorial.model.DaoSession;
import com.example.tutorial.model.Task;
import com.example.tutorial.model.TaskDao;
import com.example.tutorial.ultils.Constant;

/**
 * Xu ly broadcast khi alarm off
 * 
 * @author vanch_000
 * 
 */
public class OnAlarmReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		long taskId = intent.getExtras().getLong(Constant.KEY_TASKID);
		// luu ngam tren thiet bi
		WakeReminderIntentService.acquireStaticLock(context);
		Intent i = new Intent(context, ReminderService.class);
		i.putExtra(Constant.KEY_TASKID, taskId);

		DevOpenHelper helper = new DevOpenHelper(context, "task-db", null);
		SQLiteDatabase db = helper.getWritableDatabase();
		DaoMaster daoMaster = new DaoMaster(db);
		DaoSession daoSession = daoMaster.newSession();
		TaskDao taskDao = daoSession.getTaskDao();
		Task task = taskDao.loadByRowId(taskId);
		if (task != null) {
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setTitle(task.getTitle());
			builder.setMessage(task.getContent());
			builder.setNegativeButton("repeat", null);
			builder.setPositiveButton("sleep", null);
			AlertDialog alertDialog = builder.create();
			alertDialog.getWindow().setType(
					WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
			alertDialog.show();

			// bat dau reminder
			context.startService(i);
		}
	}

}
